package source

import (
	"io/ioutil"
	"net/http"
	"regexp"
	"strconv"
	"strings"

	"google.golang.org/appengine"
	"google.golang.org/appengine/urlfetch"
)

//获取内涵段子内容，并返回给getJoke/getPic函数处理
func get(urlStr string, req *http.Request) string {
	// cookieJar, _ := cookiejar.New(nil)
	// client := &http.Client{Jar: cookieJar}
	c := appengine.NewContext(req) //gae不允许defaultClient&defaultTransport
	client := urlfetch.Client(c)   //此处client不需要Jar
	req, err := http.NewRequest("GET", urlStr, nil)
	CheckErr(err)
	//添加请求cookie，否则会返回同一静态文本
	cookie := http.Cookie{}
	cookie.Name = "tt_webid"
	cookie.Value = "3363383210"
	req.AddCookie(&cookie)
	res, err := client.Do(req)
	CheckErr(err)
	defer res.Body.Close()
	input, err := ioutil.ReadAll(res.Body)
	CheckErr(err)
	return string(input)
}

//Joke 返回内涵社区段子内容
func Joke(urlStr string, req *http.Request) string {
	content := get(urlStr, req)
	r := regexp.MustCompile(`(?s)<div class="detail-wrapper">.*?<div class="options"`)
	text := r.FindAllString(content, -1)
	content = ""
	for i, txt := range text {
		r := regexp.MustCompile(`<p>.*?</p>`)
		msg := r.FindAllString(txt, -1)
		if len(msg) == 1 {
			content += strconv.Itoa(i+1) + "、" + msg[0]
		} else {
			content += strconv.Itoa(i+1) + "、" + msg[0] + "神评论：" + msg[1]
		}
	}
	content = strings.Replace(content, "<p>", "", -1)
	content = strings.Replace(content, "</p>", "\n", -1)
	content = strings.Replace(content, "<br />", "\n", -1)
	content = strings.Replace(content, "&quot;", " ", -1)
	return content
}

//Pic 返回内涵社区囧图内容
func Pic(urlStr string, req *http.Request) string {
	content := get(urlStr, req)
	r := regexp.MustCompile(`(?s)<div class="img-wrapper">.*?<li class="post-comment-btn right">`)
	text := r.FindAllString(content, -1)
	content = ""
	for i, txt := range text {
		r := regexp.MustCompile(`data-(pic|text)=".*?"\n`)
		msg := r.FindAllString(txt, -1)
		if len(msg) == 2 {
			msg[1] = strings.Replace(msg[1], `data-pic="`, "[img]", -1)
			msg[1] = strings.Replace(msg[1], "\"\n", "[/img]\n", -1)
			content += strconv.Itoa(i+1) + "、" + msg[0] + msg[1]
		}
		r = regexp.MustCompile(`<p>.*?</p>`)
		if r.MatchString(txt) {
			content += "神评论：" + r.FindString(txt)
		}
	}
	content = strings.Replace(content, "\"\n", "\n", -1)
	content = strings.Replace(content, "<p>", "", -1)
	content = strings.Replace(content, "</p>", "\n", -1)
	content = strings.Replace(content, "<br />", "\n", -1)
	content = strings.Replace(content, "&quot;", " ", -1)
	content = strings.Replace(content, `data-text="`, "", -1)
	return content
}
